package types // import "xemo.top/docker/docker/api/types"
import (
	"io"
	"os"
	"time"

	"github.com/docker/go-connections/nat"
	"xemo.top/docker/docker/api/types/container"
	"xemo.top/docker/docker/api/types/filters"
	"xemo.top/docker/docker/api/types/mount"
	"xemo.top/docker/docker/api/types/network"
)

// ConfigListOptions 保存参数以列出配置
// ConfigListOptions holds parameters to list configs
type ConfigListOptions struct {
	Filters filters.Args
}

// ConfigCreateResponse 包含在创建新配置时返回给客户端的信息。
// ConfigCreateResponse contains the information returned to a client on the creation of a new config.
type ConfigCreateResponse struct {
	// ID is the id of the created config
	ID string
}

// ExecStartCheck是execStart使用的临时结构体
// ExecStartCheck is a temp struct used by execStart
// Config字段是runconfig包中ExecConfig的一部分
// Config fields is part of ExecConfig in runconfig package
type ExecStartCheck struct {
	//ExecStart将首先检查它是否已分离
	// ExecStart will first check if it's detached
	Detach bool
	// Check if there's a tty
	Tty bool
}

// ContainerJSON是与MountPoint一起新使用的结构体
// ContainerJSON is newly used struct along with MountPoint
type ContainerJSON struct {
	*ContainerJSONBase
	Mounts          []MountPoint
	Config          *container.Config
	NetworkSettings *NetworkSettings
}

// NetworkSettings 在api中公开网络设置
// NetworkSettings exposes the network settings in the api
type NetworkSettings struct {
	NetworkSettingsBase
	DefaultNetworkSettings
	Networks map[string]*network.EndpointSettings
}

// DefaultNetworkSettings 在2版本弃用期间保存网络信息。
// DefaultNetworkSettings holds network information during the 2 release deprecation period.
// It will be removed in Docker 1.11.
type DefaultNetworkSettings struct {
	// EndpointID 唯一地表示沙盒中的服务端点
	// EndpointID uniquely represents a service endpoint in a Sandbox
	EndpointID string
	// Gateway 保存网络的网关地址
	// Gateway holds the gateway address for the network
	Gateway string
	//GlobalIPv6Address保存网络的全球IPv6地址
	// GlobalIPv6Address holds network's global IPv6 address
	GlobalIPv6Address string
	//GlobalIPv6PrefixLen表示网络全局IPv6地址的掩码长度
	// GlobalIPv6PrefixLen represents mask length of network's global IPv6 address
	GlobalIPv6PrefixLen int
	//IPAddress保存网络的IPv4地址
	// IPAddress holds the IPv4 address for the network
	IPAddress string
	// IPPrefixLen 表示网络IPv4地址的掩码长度
	// IPPrefixLen represents mask length of network's IPv4 address
	IPPrefixLen int
	//IPv6Gateway 保存IPv6专用的网关地址
	// IPv6Gateway holds gateway address specific for IPv6
	IPv6Gateway string
	// MacAddress 保存网络的MAC地址
	// MacAddress holds the MAC address for the network
	MacAddress string
}

// NetworkSettingsBase 包含有关网络的基本信息
// NetworkSettingsBase holds basic information about networks
type NetworkSettingsBase struct {
	// Bridge 是网络使用的网桥名称（例如“docker0”）
	// Bridge is the Bridge name the network uses(e.g. `docker0`)
	Bridge string
	// SandboxID 唯一地表示容器的网络堆栈
	// SandboxID uniquely represents a container's network stack
	SandboxID string
	// HairpinMode 指定是否应在虚拟接口上启用发夹NAT
	// HairpinMode specifies if hairpin NAT should be enabled on the virtual interface
	HairpinMode bool
	// LinkLocalIPv6Address 是一个使用链路本地前缀的IPv6单播地址
	// LinkLocalIPv6Address is an IPv6 unicast address using the link-local prefix
	LinkLocalIPv6Address string
	// LinkLocalIPv6PrefixLen 是IPv6单播地址的前缀长度
	// LinkLocalIPv6PrefixLen is the prefix length of an IPv6 unicast address
	LinkLocalIPv6PrefixLen int
	// Ports 是按Port索引的PortBinding的集合
	// Ports is a collection of PortBinding indexed by Port
	Ports nat.PortMap
	//SandboxKey标识沙盒
	// SandboxKey identifies the sandbox
	SandboxKey             string
	SecondaryIPAddress     []network.Address
	SecondaryIPv6Addresses []network.Address
}

// MountPoint 表示容器内的装载点配置。
// MountPoint represents a mount point configuration inside the container.
// 这用于报告容器正在使用的装载点。
// This is used for reporting the mountpoints in use by a container.
type MountPoint struct {
	Type        mount.Type `json:",omitempty"`
	Name        string     `json:",omitempty"`
	Source      string
	Destination string
	Driver      string `json:",omitempty"`
	Mode        string
	RW          bool
	Propagation mount.Propagation
}

// ContainerJSONBase包含引擎API的响应：
// ContainerJSONBase contains response of Engine API:
// GET "/containers/{name:.*}/json"
type ContainerJSONBase struct {
	ID              string `json:"Id"`
	Created         string
	Path            string
	Args            []string
	State           *ContainerState
	Image           string
	ResolvConfPath  string
	HostnamePath    string
	HostsPath       string
	LogPath         string
	Node            *ContainerNode `json:",omitempty"`
	Name            string
	RestartCount    int
	Driver          string
	Platform        string
	MountLabel      string
	ProcessLabel    string
	AppArmorProfile string
	ExecIDs         []string
	HostConfig      *container.HostConfig
	GraphDriver     GraphDriverData
	SizeRw          *int64 `json:",omitempty"`
	SizeRootFs      *int64 `json:",omitempty"`
}

// ContainerNode存储有关正在运行容器的节点的信息。它仅在Docker Swarm中可用
// ContainerNode stores information about the node that a container is running on.It's only available in Docker Swarm
type ContainerNode struct {
	ID        string
	IPAddress string `json:"IP"`
	Addr      string
	Name      string
	Cpus      int
	Memory    int64
	Labels    map[string]string
}

// ContainerState存储容器的运行状态，它是ContainerJSONBase的一部分，将通过“inspect”命令返回
// ContainerState stores container's running state it's part of ContainerJSONBase and will return by "inspect" command
type ContainerState struct {
	//容器状态的字符串表示。可以是“已创建”、“正在运行”、“已暂停”、“重新启动”、“删除”、“退出”或“已终止”之一
	// String representation of the container state. Can be one of "created","running","paused","restarting","removing","exited",or "dead"
	Status     string
	Running    bool
	Paused     bool
	Restarting bool
	OOMKilled  bool
	Dead       bool
	Pid        int
	ExitCode   int
	Error      string
	StartedAt  string
	FinishedAt string
	Health     *Health `json:",omitempty"`
}

// 健康存储有关容器健康检查结果的信息
// Health stores information about the container's healthcheck results
type Health struct {
	//状态是开始、健康或不健康
	// Status is one of Starting,Healthy or Unhealthy
	Status string
	//FailingStreak是连续失败的次数
	// FailingStreak is the number of consecutive failures
	FailingStreak int
	//日志包含最后几个结果（最旧的先到
	// Log contains the last few results (oldest first)
	Log []*HealthcheckResult
}

// HealthcheckResult存储有关健康检查探针单次运行的信息
// HealthcheckResult stores information about a single run of a healthcheck probe
type HealthcheckResult struct {
	//Start是此检查开始的时间
	// Start is the time this check started
	Start time.Time
	//End是此检查结束的时间
	// End is the time this check ended
	End time.Time
	//ExitCode含义：0=健康，1=不健康，2=保留（被认为不健康），else=运行探测时出错
	// ExitCode meanings: 0=healthy,1=unhealthy,2=reserved(considered unhealthy),else=error running probe
	ExitCode int
	//上次检查的输出
	// Output from last check
	Output string
}

// Container contains response of Engine API:
// GET "/containers/json"
type Container struct {
	ID         string `json:"Id"`
	Names      []string
	Image      string
	ImageID    string
	Command    string
	Created    int64
	Ports      []Port
	SizeRw     int64 `json:",omitempty"`
	SizeRootFs int64 `json:",omitempty"`
	Labels     map[string]string
	State      string
	Status     string
	HostConfig struct {
		NetworkMode string `json:",omitempty"`
	}
	NetworkSettings *SummaryNetworkSettings
	Mounts          []MountPoint
}

// SummaryNetworkSettings 提供容器网络的摘要
// SummaryNetworkSettings provides a summary of container's networks
// in /containers/json
type SummaryNetworkSettings struct {
	Networks map[string]*network.EndpointSettings
}

// ContainerPathStat 用于对来自的标头进行编码
// ContainerPathStat is used to encode the header from
// GET "/containers/{name:.*}/archive"
// "Name" is the file or directory name
type ContainerPathStat struct {
	Name       string      `json:"name"`
	Size       int64       `json:"size"`
	Mode       os.FileMode `json:"mode"`
	Mtime      time.Time   `json:"mtime"`
	LinkTarget string      `json:"linkTarget"`
}

// ContainerStats 包含引擎API的响应：
// ContainerStats contains response of Engine API:
// GET "/stats"
type ContainerStats struct {
	Body   io.ReadCloser `json:"body"`
	OSType string        `json:"ostype"`
}

// ContainersPruneReport contains the response for Engine API:
// POST "/containers/prune"
type ContainersPruneReport struct {
	ContainersDeleted []string
	SpaceReclaimed    uint64
}

// BuildCachePruneOptions hold parameters to prune the build cache
type BuildCachePruneOptions struct {
	All         bool
	KeepStorage int64
	Filters     filters.Args
}

// BuildCachePruneReport 包含引擎API的响应: POST “/build/prune”
// BuildCachePruneReport contains the response for Engine API: POST "/build/prune"
type BuildCachePruneReport struct {
	CachesDeleted  []string
	SpaceReclaimed uint64
}

// ImageInspect 包含引擎API的响应: GET “/images/{name:.*}/json”
// ImageInspect contains response of Engine API: GET "/images/{name:.*}/json"
type ImageInspect struct {
	ID              string `json:"Id"`
	RepoTags        []string
	RepoDigests     []string
	Parent          string
	Comment         string
	Created         string
	Container       string
	ContainerConfig *container.Config
	DockerVersion   string
	Author          string
	Config          *container.Config
	Architecture    string
	Os              string
	Osversion       string `json:",omitempty"`
	Size            int64
	VirtualSize     int64
	GraphDriver     GraphDriverData
	RootFS          RootFS
	Metadata        ImageMetadata
}

// ImageMetadata 包含有关图像的引擎本地数据
// ImageMetadata contains engine-local data about the image
type ImageMetadata struct {
	LastTagTime time.Time `json:",omitempty"`
}

// RootFS 返回图像的RootFS描述，包括层id。
// RootFS returns Image's RootFS description including the layer IDs.
type RootFS struct {
	Type      string
	Layers    []string `json:",omitempty"`
	BaseLayer string   `json:",omitempty"`
}

// ImagesPruneReport 包含引擎API的响应: POST “/images/prune”
// ImagesPruneReport contains the response for Engine API: POST "/images/prune"
type ImagesPruneReport struct {
	ImagesDeleted  []ImageDeleteResponseItem
	SpaceReclaimed uint64
}

// NetworkCreate 是 “create network” http请求消息的预期正文
// NetworkCreate is the expected body of the "create network" http request message
type NetworkCreate struct {
	// 检查具有重复名称的网络。网络主要基于随机ID而不是名称进行键控。网络名称严格来说是使用ID唯一标识的网络的用户友好别名。选项CheckDuplicate是为了提供对具有相同名称的任何网络的最大努力检查，但不能保证捕获所有名称冲突。
	// Check for networks with duplicate names. Network is primarily keyed based on a random ID and not on the name.Network name is strictly a user-friendly alias to the network which is uniquely identified using ID. And there is no guaranteed way to check for duplicates.Option CheckDuplicate is there to provide a best effort checking of any networks which has the same name but it is not guaranteed to catch all name collisions.
	CheckDuplicate bool
	Driver         string
	Scope          string
	EnableIPv6     bool
	IPAM           *network.IPAM
	Internal       bool
	Attachable     bool
	Ingress        bool
	ConfigOnly     bool
	ConfigFrom     *network.ConfigReference
	Options        map[string]string
	Labels         map[string]string
}

// NetworkCreateRequest 是发送到服务器进行网络创建调用的请求消息。
// NetworkCreateRequest is the request message sent to the server for network create call.
type NetworkCreateRequest struct {
	NetworkCreate
	Name string
}

// NetworkCreateResponse 是服务器为网络创建调用发送的响应消息
// NetworkCreateResponse is the response message sent by the server for network create call
type NetworkCreateResponse struct {
	ID      string `json:"Id"`
	Warning string
}

// NetworkInspectOptions holds parameters to inspect network
type NetworkInspectOptions struct {
	Scope   string
	Verbose bool
}

// NetworkResource 是 “get network” http响应消息的主体
// NetworkResource is the body of the "get network" http response message
type NetworkResource struct {
	// Name 是请求的网络名称
	// Name is the requested name of the network
	Name string
	// ID 唯一标识网络一台机器
	// ID uniquely identifies a network an a single machine
	ID string
	// Created 是网络创建的时间
	// Created is the time the network created
	Created time.Time
	// Scope 描述网络存在的级别 (例如，群集范围的 “群” 或机器级别的 “本地”)
	// Scope describes the level at which the network exists (e.g. `swarm` for cluster-wide or `local` for machine level)
	Scope string
	// Driver 是用于创建网络的驱动程序名称 (例如 'bridge'，'overlay')
	// Driver is the Driver name used to create the network (e.g. `bridge`,`overlay`)
	Driver string
	// EnableIPv6 表示是否启用IPv6
	// EnableIPv6 represents whether to enable IPv6
	EnableIPv6 bool
	// IPAM 是网络的ip地址管理
	// IPAM is the network's IP Address Management
	IPAM network.IPAM
	// Internal 表示网络是否仅在内部使用
	// Internal represents if the network is used internal only
	Internal bool
	// Attachable 表示全局范围是否可通过swarm模式下的worker中的常规容器手动附加。
	// Attachable represents if the global scope is manually attachable by regular containers from workers in swarm mode.
	Attachable bool
	// Ingress 表示网络正在为swarm集群提供路由网格。
	// Ingress indicates the network is providing the routing-mesh for the swarm cluster.
	Ingress bool
	// ConfigFrom 指定将为此网络提供配置的源。
	// ConfigFrom specifies the source which will provide the configuration for this network.
	ConfigFrom network.ConfigReference
	// ConfigOnly 网络是占位网络，用于其他网络使用网络配置。ConfigOnly网络不能直接用于运行容器或服务。
	// ConfigOnly networks are place-holder networks for network configurations to be used by other networks.ConfigOnly networks cannot be used directly to run containers or services.
	ConfigOnly bool
	// Containers 包含属于网络的端点
	// Containers contains endpoints belonging to the network
	Containers map[string]EndpointResource
	// Options 保存创建网络时要使用的网络特定选项
	// Options holds the network specific options to use for when creating the network
	Options map[string]string
	// Labels 保存特定于正在创建的网络的元数据
	// Labels holds metadata specific to the network being created
	Labels map[string]string
	// List 覆盖网络的对等模式
	// List of peer mode for an overlay network
	Peers    []network.PeerInfo             `json:",omitempty"`
	Services map[string]network.ServiceInfo `json:",omitempty"`
}

// EndpointResource 包含为网络中的容器分配和使用的网络资源。
// EndpointResource contains network resources allocated and used for a container in a network.
type EndpointResource struct {
	Name        string
	EndpointID  string
	MacAddress  string
	IPv4Address string
	IPv6Address string
}

// NetworksPruneReport 包含引擎API的响应: POST “/networks/prune”
// NetworksPruneReport contains the response for Engine API: POST "/networks/prune"
type NetworksPruneReport struct {
	NetworksDeleted []string
}

// SecretListOptions holds parameters to list secrets
type SecretListOptions struct {
	Filters filters.Args
}

// SecretCreateResponse 包含在创建新密钥时返回给客户端的信息。
// SecretCreateResponse contains the information returned to a client on the creation of a new secret.
type SecretCreateResponse struct {
	// ID is the id of the created secret.
	ID string
}

// VolumesPruneReport contains the response for Engine API: POST "/volumes/prune"
type VolumesPruneReport struct {
	VolumesDeleted []string
	SpaceReclaimed uint64
}

// ComponentVersion describes the version information for a specific component
type ComponentVersion struct {
	Name    string
	Version string
	Details map[string]string `json:",omitempty"`
}

// Version contains response of Engine API: GET "/version"
type Version struct {
	Platform   struct{ Name string } `json:",omitempty"`
	Components []ComponentVersion    `json:",omitempty"`

	// 以下字段已弃用，它们与引擎组件相关，并保留用于向后兼容
	// The following fields are deprecated,they relate to the Engine component and are kept for backwards compatibility
	Version       string
	APIVersion    string `json:"ApiVersion"`
	MinAPIVersion string `json:"MinAPIVersion,omitempty"`
	GitCommit     string
	GoVersion     string
	Os            string
	Arch          string
	KernelVersion string `json:",omitempty"`
	Experimental  bool   `json:",omitempty"`
	BuildTime     string `json:",omitempty"`
}

// Ping contains response of Engine API: GET "/_ping"
type Ping struct {
	APIVersion     string
	OSType         string
	Experimental   bool
	BuilderVersion BuilderVersion
}
